- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathstack using linked list.cpp
86 lines (68 loc) · 1.51 KB
/
stack using linked list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<iostream>
usingnamespacestd;
// Stack implementation using Linked List
// class for _stack
class_stack
{
// private data---->
// node structure
structnode
{
int data;
node* next;
};
node* head = NULL;
int n = 0;// for size of stack
public:
// public data---->
// push fuction
voidpush(int a) {
// making node
node* temp = newnode();
// check whether a stack overflows or not
if(temp==NULL){cout<<"Stack Overflow\n";return;}
// adding nodes at the beginning of linkked list
temp->data = a;
temp->next = head;
head = temp;
n++;// increamenting size
}
// pop function
voidpop() {
// check stack is empty or not
if (head == NULL) {cout << "Empty stack\n"; return;}
// points temp node pointer to the top
node *temp = head;
// move head to next node
head = head->next;
// delete temp node pointer
delete(temp);
n--;// decreamenting size
}
// top function
inttop() {
// check stack is empty or not
if (head == NULL) {cout << "Empty stack"; return -1;}
// return top node data
return head->data;
}
// stack emptly check function
boolisEmpty() {
if (head == NULL)returntrue;
elsereturnfalse;
}
// function for returning the size of stack
intsize() { return n;}
};
intmain() {
_stack s;
// user/random inputs..
for (int i = 0; i < 10; ++i) {int a; cin >> a; s.push(a); cout << s.top() << endl;}
s.pop();
s.pop();
cout << s.isEmpty() << endl;
cout << s.top() << endl;
s.push(121);
cout << s.top() << endl;
return0;
}